package StudyCode.summary.myfile;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReturnParentFileString {
	private static final String SEPARATOR = "/";

	public static void main(String[] args) {
		System.out.println("E:/Copy/1/2 的父目录是: " + parentPathString("E:/Copy/1/2"));
	}

	public static String parentPathString(String path) {
		String[] split = cleanPath(path).split(SEPARATOR);
		if (split.length > 1) {
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < split.length - 1; i++) {
				if (i > 0) {
					stringBuilder.append(SEPARATOR);
				}
				stringBuilder.append(split[i]);
			}
			return stringBuilder.toString();
		}
		return "";
	}


	private static String cleanPath(String path) {
		if (path.endsWith(SEPARATOR)) {
			path = path.replaceAll(SEPARATOR + "+$", "");
		}
		if (path.startsWith(SEPARATOR)) {
			path = path.replaceAll("^" + SEPARATOR + "+", "");
		}
		return path.replaceAll("/+", SEPARATOR);
	}
}
